<template>
  <div class="box-container">
    {{ props.label }}
    <a-select
      ref="select"
      v-model:value="curSelect"
      :style="{ width: props.width }"
      @change="handleChange"
    >
      <a-select-option
        v-for="(item, index) in options"
        :key="index"
        :value="item.text"
        >{{ item.text }}</a-select-option
      >
    </a-select>
  </div>
</template>
<script setup>
import { toRaw } from "vue";

const curSelect = ref(""); // 当前选择的模型名称
const options = ref([]); // 模型选项
const lastItem = ref(null);

const props = defineProps({
  options: {
    type: Array,
    default: () => [],
  },
  label: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "220px",
  },
});

watch(
  () => props.options,
  () => {
    options.value = toRaw(props.options);
    // 默认选中第一个
    if (options.value && options.value.length > 0) {
      curSelect.value = options.value[0].text;
      options.value[0].onselect();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

// 点击改变了
const handleChange = (val) => {
  const opt = options.value.find((item) => item.text === curSelect.value);
  opt?.onselect();

  // 如果上次选择与这次不一样，执行上次的 onUnSelect() 事件
  if (lastItem.value) {
    if (lastItem.value.text !== curSelect.value) {
      lastItem.value.onUnSelect && lastItem.value.onUnSelect();
    }
  }
  // 更新上次选择
  lastItem.value = opt;
};
</script>

<style scoped>
.box-container {
  margin-bottom: 10px;
}
</style>
